from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app.models import User, Role, Permission
from app.utils.permissions import admin_required
from app import db
from app.utils.response import response_success, response_fail

admin_api_bp = Blueprint('admin_api', __name__, url_prefix='/api/admin')

# 用户管理API
@admin_api_bp.route('/users', methods=['POST'])
@login_required
@admin_required
def create_user():
    """创建用户"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('username') or not data.get('email') or not data.get('password'):
            return response_fail(msg="用户名、邮箱和密码不能为空")
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return response_fail(msg="用户名已存在")
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=data['email']).first():
            return response_fail(msg="邮箱已被注册")
        
        # 创建新用户
        user = User(
            username=data['username'],
            email=data['email'],
            nickname=data.get('nickname', ''),
            is_active=data.get('is_active', True)
        )
        user.set_password(data['password'])
        
        # 分配角色
        if data.get('roles'):
            roles = Role.query.filter(Role.id.in_(data['roles'])).all()
            user.roles = roles
        
        db.session.add(user)
        db.session.commit()
        
        return response_success(data={
            'user': user.to_dict()
        }, msg="用户创建成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"创建用户失败: {str(e)}")

@admin_api_bp.route('/users/<int:user_id>', methods=['PUT'])
@login_required
@admin_required
def update_user(user_id):
    """更新用户"""
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json()
        
        # 更新用户信息
        if 'username' in data:
            # 检查用户名是否已存在（排除当前用户）
            if User.query.filter(User.username == data['username'], User.id != user_id).first():
                return response_fail(msg="用户名已存在")
            user.username = data['username']
        
        if 'email' in data:
            # 检查邮箱是否已存在（排除当前用户）
            if User.query.filter(User.email == data['email'], User.id != user_id).first():
                return response_fail(msg="邮箱已被注册")
            user.email = data['email']
        
        if 'nickname' in data:
            user.nickname = data['nickname']
        
        if 'is_active' in data:
            user.is_active = data['is_active']
        
        if 'is_admin' in data:
            user.is_admin = data['is_admin']
        
        if 'password' in data and data['password']:
            user.set_password(data['password'])
        
        db.session.commit()
        
        return response_success(data={
            'user': user.to_dict()
        }, msg="用户更新成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"更新用户失败: {str(e)}")

@admin_api_bp.route('/users/<int:user_id>', methods=['DELETE'])
@login_required
@admin_required
def delete_user(user_id):
    """删除用户"""
    try:
        user = User.query.get_or_404(user_id)
        
        # 不允许删除自己
        if user.id == current_user.id:
            return response_fail(msg="不能删除自己的账户")
        
        db.session.delete(user)
        db.session.commit()
        
        return response_success(msg="用户删除成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"删除用户失败: {str(e)}")

@admin_api_bp.route('/users/<int:user_id>/roles', methods=['GET'])
@login_required
@admin_required
def get_user_roles(user_id):
    """获取用户角色"""
    try:
        user = User.query.get_or_404(user_id)
        roles = [role.id for role in user.roles]
        
        return response_success(data={
            'roles': roles
        })
    
    except Exception as e:
        return response_fail(msg=f"获取用户角色失败: {str(e)}")

@admin_api_bp.route('/users/<int:user_id>/roles', methods=['POST'])
@login_required
@admin_required
def update_user_roles(user_id):
    """更新用户角色"""
    try:
        user = User.query.get_or_404(user_id)
        data = request.get_json()
        
        # 获取新角色
        new_roles = []
        if data.get('roles'):
            new_roles = Role.query.filter(Role.id.in_(data['roles'])).all()
        
        # 更新用户角色
        user.roles = new_roles
        db.session.commit()
        
        return response_success(msg="用户角色更新成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"更新用户角色失败: {str(e)}")

# 角色管理API
@admin_api_bp.route('/roles', methods=['POST'])
@login_required
@admin_required
def create_role():
    """创建角色"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return response_fail(msg="角色名称不能为空")
        
        # 检查角色名称是否已存在
        if Role.query.filter_by(name=data['name']).first():
            return response_fail(msg="角色名称已存在")
        
        # 创建新角色
        role = Role(
            name=data['name'],
            description=data.get('description', '')
        )
        
        # 分配权限
        if data.get('permissions'):
            permissions = Permission.query.filter(Permission.id.in_(data['permissions'])).all()
            role.permissions = permissions
        
        db.session.add(role)
        db.session.commit()
        
        return response_success(data={
            'role': {
                'id': role.id,
                'name': role.name,
                'description': role.description
            }
        }, msg="角色创建成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"创建角色失败: {str(e)}")

@admin_api_bp.route('/roles/<int:role_id>', methods=['PUT'])
@login_required
@admin_required
def update_role(role_id):
    """更新角色"""
    try:
        role = Role.query.get_or_404(role_id)
        data = request.get_json()
        
        # 更新角色信息
        if 'name' in data:
            # 检查角色名称是否已存在（排除当前角色）
            if Role.query.filter(Role.name == data['name'], Role.id != role_id).first():
                return response_fail(msg="角色名称已存在")
            role.name = data['name']
        
        if 'description' in data:
            role.description = data['description']
        
        db.session.commit()
        
        return response_success(data={
            'role': {
                'id': role.id,
                'name': role.name,
                'description': role.description
            }
        }, msg="角色更新成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"更新角色失败: {str(e)}")

@admin_api_bp.route('/roles/<int:role_id>', methods=['DELETE'])
@login_required
@admin_required
def delete_role(role_id):
    """删除角色"""
    try:
        role = Role.query.get_or_404(role_id)
        
        # 不允许删除admin角色
        if role.name == 'admin':
            return response_fail(msg="不能删除admin角色")
        
        db.session.delete(role)
        db.session.commit()
        
        return response_success(msg="角色删除成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"删除角色失败: {str(e)}")

@admin_api_bp.route('/roles/<int:role_id>/permissions', methods=['GET'])
@login_required
@admin_required
def get_role_permissions(role_id):
    """获取角色权限"""
    try:
        role = Role.query.get_or_404(role_id)
        permissions = [permission.id for permission in role.permissions]
        
        return response_success(data={
            'permissions': permissions
        })
    
    except Exception as e:
        return response_fail(msg=f"获取角色权限失败: {str(e)}")

@admin_api_bp.route('/roles/<int:role_id>/permissions', methods=['POST'])
@login_required
@admin_required
def update_role_permissions(role_id):
    """更新角色权限"""
    try:
        role = Role.query.get_or_404(role_id)
        data = request.get_json()
        
        # 获取新权限
        new_permissions = []
        if data.get('permissions'):
            new_permissions = Permission.query.filter(Permission.id.in_(data['permissions'])).all()
        
        # 更新角色权限
        role.permissions = new_permissions
        db.session.commit()
        
        return response_success(msg="角色权限更新成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"更新角色权限失败: {str(e)}")

# 权限管理API
@admin_api_bp.route('/permissions', methods=['POST'])
@login_required
@admin_required
def create_permission():
    """创建权限"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name') or not data.get('code'):
            return response_fail(msg="权限名称和代码不能为空")
        
        # 检查权限代码是否已存在
        if Permission.query.filter_by(code=data['code']).first():
            return response_fail(msg="权限代码已存在")
        
        # 创建新权限
        permission = Permission(
            name=data['name'],
            code=data['code'],
            description=data.get('description', '')
        )
        
        db.session.add(permission)
        db.session.commit()
        
        return response_success(data={
            'permission': {
                'id': permission.id,
                'name': permission.name,
                'code': permission.code,
                'description': permission.description
            }
        }, msg="权限创建成功")
    
    except Exception as e:
        db.session.rollback()
        return response_fail(msg=f"创建权限失败: {str(e)}")

@admin_api_bp.route('/permissions/<int:permission_id>/roles', methods=['GET'])
@login_required
@admin_required
def get_permission_roles(permission_id):
    """获取拥有指定权限的角色"""
    try:
        permission = Permission.query.get_or_404(permission_id)
        roles = []
        
        for role in permission.roles:
            roles.append({
                'id': role.id,
                'name': role.name,
                'description': role.description,
                'user_count': len(role.users)
            })
        
        return response_success(data={
            'roles': roles
        })
    
    except Exception as e:
        return response_fail(msg=f"获取角色列表失败: {str(e)}")